package com.xzw.cameratest.fragment;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.android.business.adapter.DataAdapterImpl;
import com.android.business.entity.ChannelInfo;
import com.android.business.entity.PtzPrePointInfo;
import com.android.business.exception.BusinessException;
import com.xzw.cameratest.R;
import com.xzw.cameratest.adapter.PresetPositionAdapter;
import com.xzw.cameratest.async.AsyncBuilder;

import java.util.List;


public class PresetPositionDialogFragment extends DialogFragment {

    private RecyclerView mRvPresetPosition;
    private ChannelInfo mChannelInfo;
    private AppCompatActivity mActivity;

    public static PresetPositionDialogFragment getInstance(Bundle bundle) {
        PresetPositionDialogFragment presetPositionDialogFragment = new PresetPositionDialogFragment();
        presetPositionDialogFragment.setArguments(bundle);
        return presetPositionDialogFragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        this.getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view = inflater.inflate(R.layout.fragment_preset_position_dialog, container, false);
        mRvPresetPosition = view.findViewById(R.id.rv_preset_position);
        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mActivity = (AppCompatActivity) context;
    }

    @Override
    public void onStart() {
        super.onStart();
        Window dialogWindow = getDialog().getWindow();
        if (dialogWindow != null) {
            dialogWindow.getDecorView().setPadding(0, 0, 0, 0);
            dialogWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = dp2px(300);
            lp.gravity = Gravity.BOTTOM;
            lp.windowAnimations = android.R.style.Animation_InputMethod;
            dialogWindow.setAttributes(lp);
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getArguments() != null) {
            mChannelInfo = (ChannelInfo) getArguments().getSerializable("channelInfo");
        }
        mRvPresetPosition.setLayoutManager(new LinearLayoutManager(getActivity()));
        getPresetPositions();
    }


    /**
     * 获取预置点信息
     */
    protected void getPresetPositions() {
        AsyncBuilder.createTask(new AsyncBuilder.BusinessTask<List<PtzPrePointInfo>>() {
            @Override
            public List<PtzPrePointInfo> doInBackground() throws Exception {
                /**
                 * var1 channelId 通道ID
                 */
                return DataAdapterImpl.getInstance().queryPtzPrePoints(mChannelInfo.getChnSncode());
            }
        }).resultInMain(this, new AsyncBuilder.ResultListener<List<PtzPrePointInfo>>() {
            @Override
            public void onSuccess(List<PtzPrePointInfo> data) {
                PresetPositionAdapter presetPositionAdapter = new PresetPositionAdapter(getActivity(), data);
                mRvPresetPosition.setAdapter(presetPositionAdapter);
                presetPositionAdapter.setOnItemClickListener(new PresetPositionAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(View v, PtzPrePointInfo info) {
                        setPresetPositions(info);
                        dismiss();
                    }
                });
            }

            @Override
            public void onError(BusinessException e) {

            }
        });
    }

    /**
     * 设置预置点信息（定位）
     */
    protected void setPresetPositions(final PtzPrePointInfo info) {
        AsyncBuilder.createTask(new AsyncBuilder.BusinessTask<Integer>() {
            @Override
            public Integer doInBackground() throws Exception {
                /**
                 * var1 预置点操作（locate定位）
                 * var2 channelId 通道ID
                 * var3 预置点Code
                 * var4 预置点名称
                 * var5 默认空即可
                 */
                return DataAdapterImpl.getInstance().operatePtzPrePoint(PtzPrePointInfo.PtzPrePointOperation.locate, mChannelInfo.getUuid(), info.getCode(), info.getName(), "");
            }
        }).resultInMain(mActivity, new AsyncBuilder.ResultListener<Integer>() {
            @Override
            public void onSuccess(Integer data) {
                Toast.makeText(mActivity, mActivity.getResources().getString(R.string.preset_position_set_successfully), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(BusinessException e) {
                Toast.makeText(mActivity, mActivity.getResources().getString(R.string.preset_position_set_failed), Toast.LENGTH_SHORT).show();
            }
        });
    }

    public int dp2px(float dp) {
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        float px = dp * (metrics.densityDpi / 160f);
        return (int) px;
    }


}
